/**
 * 
 */
package database.berkeleydb;

import java.io.File;

import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.collections.StoredMap;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.log.FileManager;

/**
 * @author lionbule
 * 
 */
public class TestJeConfig {

	public static void main(String[] args) throws Exception {
		// **** public variable
		String bdbDir = "/home/bdb";

		TestJeConfig tjc = new TestJeConfig();

		Environment env = tjc.getEnvironment(bdbDir);
		Database db = tjc.getDatabase("testdb", env);

		StoredMap<String, String> map = null;

		StringBinding keyBinding = new StringBinding();
		StringBinding valueBinding = new StringBinding();

		map = new StoredMap<String, String>(db, keyBinding, valueBinding, true);

		//write and read
		long _start = System.currentTimeMillis();
		String keyPrefix = "name_";
		String value_temp = "中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人中国人";
		for(int i=0;i<10000;i++){
			map.put(keyPrefix+i, i+value_temp);
		}
		for(int i=0;i<10000;i++){
			map.get(keyPrefix+i);
		}
		System.out.println(System.currentTimeMillis()-_start);
		tjc.close(db, env);
	}

	Environment getEnvironment(String bdbDir) throws Exception {
		File dbDir = new File(bdbDir);
		if(dbDir.exists()){
			FileManager.removeFiles(dbDir);
		}
		dbDir.mkdirs();
		
		// Env config
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setTransactional(true);
		envConfig.setAllowCreate(true);
		return new Environment(new File(bdbDir), envConfig);
	}

	Database getDatabase(String dbName, Environment env) {
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setTransactional(true);
		dbConfig.setAllowCreate(true);

		return env.openDatabase(null, dbName, dbConfig);
	}

	void close(Database db, Environment env) {
		if (db != null) {
			db.close();
		}
		if (env != null) {
			env.close();
		}
	}
}
